from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from app.models import db
from app.models.user import User
from datetime import timedelta
import logging

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    logger = logging.getLogger('auth_logger')
    logger.info(f"登录请求开始 - Origin: {request.headers.get('Origin', 'None')}")
    logger.info(f"请求头: {dict(request.headers)}")
    
    try:
        # 获取请求中的json数据
        data = request.get_json()
        logger.info(f"请求数据: {data if data else 'None'}")
        
        if not data:
            logger.error("请求数据为空")
            return jsonify({'error': '请求数据不能为空'}), 400
        
        # 获取用户名和密码
        username = data.get('username')
        password = data.get('password')
        
        logger.info(f"尝试登录用户: {username}")
        
        # 如果用户名或密码为空，返回错误信息
        if not username or not password:
            logger.error("用户名或密码为空")
            return jsonify({'error': '用户名和密码不能为空'}), 400
        
        # 根据用户名查询用户
        user = User.query.filter_by(username=username).first()
        logger.info(f"用户查询结果: {'找到用户' if user else '用户不存在'}")
        
        # 如果用户不存在或密码错误，返回错误信息
        if not user or not user.check_password(password):
            logger.error(f"登录失败 - 用户名或密码错误: {username}")
            return jsonify({'error': '用户名或密码错误'}), 401
        
        # 如果用户账户被禁用，返回错误信息
        if not user.is_active:
            logger.error(f"登录失败 - 账户被禁用: {username}")
            return jsonify({'error': '账户已被禁用'}), 401
        
        # 创建访问令牌
        access_token = create_access_token(
            identity=str(user.id),
            expires_delta=timedelta(hours=24)
        )
        
        logger.info(f"登录成功 - 用户: {username}, ID: {user.id}")
        
        # 返回访问令牌和用户信息
        response = jsonify({
            'access_token': access_token,
            'user': user.to_dict()
        })
        
        # 手动添加CORS头
        origin = request.headers.get('Origin')
        if origin:
            response.headers['Access-Control-Allow-Origin'] = origin
            response.headers['Access-Control-Allow-Credentials'] = 'true'
            logger.info(f"添加CORS头 - Origin: {origin}")
        
        return response, 200
        
    except Exception as e:
        # 如果发生异常，返回错误信息
        logger.error(f"登录异常: {str(e)}", exc_info=True)
        return jsonify({'error': str(e)}), 500

@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取当前用户信息"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        return jsonify({'user': user.to_dict()}), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@auth_bp.route('/change-password', methods=['POST'])
@jwt_required()
def change_password():
    """修改密码"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        
        if not old_password or not new_password:
            return jsonify({'error': '旧密码和新密码不能为空'}), 400
        
        if not user.check_password(old_password):
            return jsonify({'error': '旧密码错误'}), 400
        
        if len(new_password) < 6:
            return jsonify({'error': '新密码长度不能少于6位'}), 400
        
        user.set_password(new_password)
        db.session.commit()
        
        return jsonify({'message': '密码修改成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500
